package com.example.openapi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.openapi.config.WaiqinApiProperties;
import com.waiqin365.openapi.tools.WQApiHandler;
import com.waiqin365.openapi.vo.WQOpenApi;
import com.waiqin365.openapi.vo.WQRequest;
import com.waiqin365.openapi.vo.WQResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 勤策OpenAPI调用服务
 *
 * @author MCP Service
 * @version 1.0.0
 */
@Slf4j
@Service
public class WaiqinApiService {

    @Autowired
    private WaiqinApiProperties properties;

    private WQOpenApi wqOpenApi;

    @PostConstruct
    public void init() {
        // 初始化勤策OpenAPI客户端
        wqOpenApi = new WQOpenApi(properties.getOpenid(), properties.getAppkey());
        wqOpenApi.setOpenurl(properties.getApiUrl());
        log.info("勤策OpenAPI客户端初始化完成");
    }

    /**
     * 调用勤策OpenAPI通用方法
     *
     * @param module    模块名称（如：organization）
     * @param version   版本号（如：v1）
     * @param operation 操作名称（如：modifyOrganization）
     * @param params    请求参数
     * @return API响应结果
     */
    public JSONObject callApi(String module, String version, String operation, Map<String, Object> params) {
        try {
            WQRequest request = new WQRequest();
            request.setWqOpenApi(wqOpenApi);
            request.setModule(module);
            request.setVersion(version);
            request.setOperation(operation);

            // 设置请求数据
            if (params != null && !params.isEmpty()) {
                JSONObject body = new JSONObject(params);
                request.setRequestdata(body.toJSONString());
                log.info("调用勤策API - Module: {}, Version: {}, Operation: {}, Params: {}",
                        module, version, operation, body.toJSONString());
            } else {
                request.setRequestdata("{}");
                log.info("调用勤策API - Module: {}, Version: {}, Operation: {}",
                        module, version, operation);
            }

            // 调用API
            WQResponse response = WQApiHandler.handleOpenApi(request);

            log.info("请求URL: {}", request.getRequestUrl());
            log.info("返回码: {}, 返回消息: {}", response.getReturn_code(), response.getReturn_msg());

            // 构建响应结果
            JSONObject result = new JSONObject();
            result.put("return_code", response.getReturn_code());
            result.put("return_msg", response.getReturn_msg());
            result.put("success", "0".equals(response.getReturn_code()));

            if (response.getResponse_data() != null) {
                result.put("data", JSON.parse(response.getResponse_data()));
            }

            return result;

        } catch (Exception e) {
            log.error("调用勤策API失败", e);
            JSONObject errorResult = new JSONObject();
            errorResult.put("success", false);
            errorResult.put("return_code", "-1");
            errorResult.put("return_msg", "API调用失败: " + e.getMessage());
            return errorResult;
        }
    }
}
